package com.eairlv.utils.validator.url;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.eairlv.utils.MSInterceptorProperties;
import com.eairlv.utils.validator.user.UserInformation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

/**
 * @author eairlv
 * @description
 * @date 16:36 2019/8/29
 */
@Slf4j
public class UrlClient {

    /**
     * 用户身份校验
     * @param restTemplate
     * @param properties
     * @return
     */
    public static UserInformation jwt(String method, String uri, String jwt, RestTemplate restTemplate, MSInterceptorProperties properties){
        if (StrUtil.isNotBlank(properties.getAuthenticationUrl())){
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
            HttpEntity<String> requestBody = new HttpEntity<>(JSON.toJSONString(UrlBO.builder()
                    .uri(uri)
                    .jwt(jwt)
                    .method(method)
                    .build()), headers);
            Result<UserInformation> userInfoResult = JSON.parseObject(restTemplate.postForObject(properties.getAuthenticationUrl(), requestBody, String.class),
                    new TypeReference<Result<UserInformation>>() {});
            if (userInfoResult.getCode() == HttpResult.SUCCESS.getCode()){
                if (userInfoResult.getData() == null){
                    return new UserInformation();
                }
                return userInfoResult.getData();
            }
        } else {
            log.error("ms-interceptor.authenticationURL is empty, please configure auth path Or set ms-interceptor.authentication=false");
        }
        return null;
    }

}
